"""
摄像头管理API端点
Camera Management API Endpoints
"""
import logging
from typing import List, Dict, Any, Optional
from fastapi import APIRouter, HTTPException, Query

from api.services import CameraService
from schemas.camera import CameraCreate, CameraUpdate, CameraResponse, CameraListResponse
from services.wvp_service_unified import get_unified_wvp_service
from database.simple_db import get_database_manager

logger = logging.getLogger(__name__)
router = APIRouter()

# 创建服务实例
camera_service = CameraService()
wvp_service = get_unified_wvp_service()
db = get_database_manager()


@router.get("/")
async def get_cameras(
    status: Optional[str] = Query(None, description="按状态筛选"),
    ai_enabled: Optional[bool] = Query(None, description="按AI启用状态筛选"),
    limit: int = Query(100, ge=1, le=1000, description="返回数量限制"),
    page: int = Query(1, ge=1, description="页码"),
    size: int = Query(100, ge=1, le=1000, description="每页数量")
):
    """获取摄像头列表"""
    try:
        cameras = await camera_service.get_cameras(
            status=status,
            ai_enabled=ai_enabled,
            limit=size  # 使用size参数
        )
        
        # 返回前端期望的格式
        return {
            "data": cameras,
            "items": cameras,  # 兼容性
            "total": len(cameras),
            "page": page,
            "size": size,
            "code": 200,
            "msg": "查询成功"
        }
    except Exception as e:
        logger.error(f"获取摄像头列表失败: {e}")
        raise HTTPException(status_code=500, detail="获取摄像头列表失败")


@router.get("/{camera_id}", response_model=CameraResponse)
async def get_camera(camera_id: str):
    """获取单个摄像头信息"""
    try:
        camera = await camera_service.get_camera(camera_id)
        if not camera:
            raise HTTPException(status_code=404, detail="摄像头不存在")
        return camera
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取摄像头信息失败: {e}")
        raise HTTPException(status_code=500, detail="获取摄像头信息失败")


@router.post("/", response_model=Dict[str, Any])
async def create_camera(camera_data: CameraCreate):
    """创建新摄像头"""
    try:
        # 验证输入数据
        if not camera_data.name and not camera_data.camera_id:
            raise HTTPException(status_code=400, detail="摄像头名称或ID不能为空")
        
        # 检查名称是否已存在
        if camera_data.name:
            existing_camera = await camera_service.get_camera(camera_data.name)
            if existing_camera:
                raise HTTPException(status_code=409, detail=f"摄像头名称 '{camera_data.name}' 已存在")
        
        # 创建摄像头
        camera_dict = camera_data.dict(exclude_unset=True)
        camera_id = await camera_service.create_camera(camera_dict)
        
        if not camera_id:
            raise HTTPException(status_code=400, detail="创建摄像头失败")
        
        # 返回创建的摄像头信息
        camera = await camera_service.get_camera(str(camera_id))
        if camera:
            return camera
        else:
            # 如果获取失败，返回基本信息
            return {
                "id": camera_id,
                "name": camera_data.name or camera_data.camera_id,
                "camera_id": camera_data.camera_id,
                "status": "created",
                "message": "摄像头创建成功"
            }
            
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"创建摄像头失败: {e}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"创建摄像头失败: {str(e)}")


@router.put("/{camera_id}", response_model=Dict[str, Any])
async def update_camera(camera_id: str, camera_data: CameraUpdate):
    """更新摄像头信息"""
    try:
        # 检查摄像头是否存在
        existing_camera = await camera_service.get_camera(camera_id)
        if not existing_camera:
            raise HTTPException(status_code=404, detail="摄像头不存在")
        
        # 更新摄像头
        update_data = {k: v for k, v in camera_data.dict().items() if v is not None}
        success = await camera_service.update_camera(camera_id, update_data)
        
        if not success:
            raise HTTPException(status_code=400, detail="更新摄像头失败")
        
        # 返回更新后的摄像头信息
        camera = await camera_service.get_camera(camera_id)
        return camera
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"更新摄像头失败: {e}")
        raise HTTPException(status_code=500, detail="更新摄像头失败")


@router.delete("/{camera_id}")
async def delete_camera(camera_id: str):
    """删除摄像头"""
    try:
        # 检查摄像头是否存在
        existing_camera = await camera_service.get_camera(camera_id)
        if not existing_camera:
            raise HTTPException(status_code=404, detail="摄像头不存在")
        
        success = await camera_service.delete_camera(camera_id)
        if not success:
            raise HTTPException(status_code=400, detail="删除摄像头失败")
        
        return {"message": "摄像头删除成功", "camera_id": camera_id}
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"删除摄像头失败: {e}")
        raise HTTPException(status_code=500, detail="删除摄像头失败")


@router.post("/{camera_id}/enable-ai")
async def enable_ai_services(camera_id: str, services: Optional[List[str]] = None):
    """启用摄像头AI服务"""
    try:
        # 检查摄像头是否存在
        existing_camera = await camera_service.get_camera(camera_id)
        if not existing_camera:
            raise HTTPException(status_code=404, detail="摄像头不存在")
        
        # 如果没有指定服务，使用默认服务
        if not services:
            services = ["behavior_monitoring", "crowd_safety"]
        
        success = await camera_service.enable_ai_services(camera_id, services)
        if not success:
            raise HTTPException(status_code=400, detail="启用AI服务失败")
        
        return {"message": "AI服务启用成功", "camera_id": camera_id, "services": services}
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"启用AI服务失败: {e}")
        raise HTTPException(status_code=500, detail="启用AI服务失败")


@router.post("/{camera_id}/disable-ai")
async def disable_ai_services(camera_id: str):
    """禁用摄像头AI服务"""
    try:
        # 检查摄像头是否存在
        existing_camera = await camera_service.get_camera(camera_id)
        if not existing_camera:
            raise HTTPException(status_code=404, detail="摄像头不存在")
        
        success = await camera_service.disable_ai_services(camera_id)
        if not success:
            raise HTTPException(status_code=400, detail="禁用AI服务失败")
        
        return {"message": "AI服务禁用成功", "camera_id": camera_id}
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"禁用AI服务失败: {e}")
        raise HTTPException(status_code=500, detail="禁用AI服务失败")


@router.get("/{camera_id}/status")
async def get_camera_status(camera_id: str):
    """获取摄像头状态"""
    try:
        status = await camera_service.get_camera_status(camera_id)
        if not status:
            raise HTTPException(status_code=404, detail="摄像头不存在")
        return status
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取摄像头状态失败: {e}")
        raise HTTPException(status_code=500, detail="获取摄像头状态失败")


# WVP相关API端点

@router.get("/wvp/devices")
async def list_wvp_devices(
    page: int = Query(1, ge=1, description="页码"),
    size: int = Query(20, ge=1, le=100, description="每页数量"),
    status: Optional[str] = Query(None, description="按状态筛选")
):
    """获取WVP设备列表"""
    try:
        # 构建查询条件
        where_clauses = []
        params = []
        
        if status:
            where_clauses.append('status = ?')
            params.append(status)
        
        where_clause = ' WHERE ' + ' AND '.join(where_clauses) if where_clauses else ''
        
        # 获取总数
        count_query = f'SELECT COUNT(*) as total FROM wvp_devices{where_clause}'
        count_result = db.execute_query(count_query, tuple(params))
        total = count_result[0]['total'] if count_result else 0
        
        # 获取分页数据
        offset = (page - 1) * size
        list_query = f'''
            SELECT * FROM wvp_devices{where_clause} 
            ORDER BY updated_at DESC 
            LIMIT ? OFFSET ?
        '''
        
        list_params = tuple(params) + (size, offset)
        devices = db.execute_query(list_query, list_params)
        
        return {
            "success": True,
            "data": {
                "rows": devices,
                "total": total,
                "page": page,
                "size": size
            },
            "message": "获取WVP设备列表成功"
        }
        
    except Exception as e:
        logger.error(f"获取WVP设备列表失败: {e}")
        raise HTTPException(status_code=500, detail="获取WVP设备列表失败")


@router.get("/wvp/devices/{device_id}/channels")
async def list_device_channels(
    device_id: str,
    page: int = Query(1, ge=1, description="页码"),
    size: int = Query(20, ge=1, le=100, description="每页数量")
):
    """获取设备通道列表"""
    try:
        # 获取总数
        count_query = 'SELECT COUNT(*) as total FROM wvp_channels WHERE device_id = ?'
        count_result = db.execute_query(count_query, (device_id,))
        total = count_result[0]['total'] if count_result else 0
        
        # 获取分页数据
        offset = (page - 1) * size
        list_query = '''
            SELECT * FROM wvp_channels 
            WHERE device_id = ? 
            ORDER BY updated_at DESC 
            LIMIT ? OFFSET ?
        '''
        
        channels = db.execute_query(list_query, (device_id, size, offset))
        
        return {
            "success": True,
            "data": {
                "rows": channels,
                "total": total,
                "page": page,
                "size": size
            },
            "message": "获取设备通道列表成功"
        }
        
    except Exception as e:
        logger.error(f"获取设备通道列表失败: {e}")
        raise HTTPException(status_code=500, detail="获取设备通道列表失败")


@router.post("/wvp/sync")
async def sync_wvp_data():
    """手动触发WVP数据同步"""
    try:
        # 执行WVP数据同步
        sync_result = await wvp_service.sync_wvp_devices_and_channels()
        
        if sync_result["success"]:
            return {
                "success": True,
                "data": sync_result["data"],
                "message": sync_result["message"]
            }
        else:
            raise HTTPException(status_code=500, detail=sync_result["message"])
            
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"WVP数据同步失败: {e}")
        raise HTTPException(status_code=500, detail="WVP数据同步失败")


@router.get("/{camera_id}/stream-info")
async def get_camera_stream_info(camera_id: int):
    """获取摄像头流信息"""
    try:
        # 从cameras表获取摄像头信息
        camera = db.get_camera_by_id(camera_id)
        if not camera:
            raise HTTPException(status_code=404, detail="摄像头不存在")
        
        # 如果cameras表中有RTSP URL，直接返回
        if camera.get('rtsp_url'):
            return {
                "success": True,
                "data": {
                    "rtsp": camera['rtsp_url'],
                    "primary_format": "rtsp",
                    "primary_url": camera['rtsp_url']
                },
                "message": "获取摄像头流信息成功"
            }
        
        # 如果没有RTSP URL，尝试从WVP通道表获取备用地址
        if camera.get('wvp_device_id') and camera.get('wvp_channel_id'):
            device_id = camera['wvp_device_id']
            channel_id = camera['wvp_channel_id']
            
            # 构建标准RTSP URL
            rtsp_url = f"rtsp://localhost:554/rtp/{device_id}_{channel_id}"
            
            # 更新cameras表中的RTSP URL
            db.execute_update(
                "UPDATE cameras SET rtsp_url = ? WHERE id = ?",
                (rtsp_url, camera_id)
            )
            
            return {
                "success": True,
                "data": {
                    "rtsp": rtsp_url,
                    "primary_format": "rtsp",
                    "primary_url": rtsp_url
                },
                "message": "获取摄像头流信息成功"
            }
        
        raise HTTPException(status_code=404, detail="无法获取摄像头流信息")
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取摄像头流信息失败: {e}")
        raise HTTPException(status_code=500, detail="获取摄像头流信息失败")